package com.google.gwt.it2tool.client.widget;

import java.util.ArrayList;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.it2tool.client.widget.MassProductionPanel.IMassProductionChangedHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class AddFactoryPanel extends HorizontalPanel {
	
	private ArrayList<IFactoryAddedHandler> addHandlers = new ArrayList<IFactoryAddedHandler>();
	
	
	//Header
	private Label addFactoryLabel = new Label("Fabrik hinzufügen");
	//Header+content
	private VerticalPanel body = new VerticalPanel();
	private HorizontalPanel content = new HorizontalPanel();
	private TextBox newFactoryNameTextBox = new TextBox();
	private Button addFactoryButton = new Button("hinzufügen");
	
	public AddFactoryPanel(){
		super();
		
		addFactoryLabel.addStyleName("addFactoryLabel");
		newFactoryNameTextBox.addStyleName("newFactoryNameTextBox");
		
		content.add(newFactoryNameTextBox);
		content.add(addFactoryButton);
		body.add(addFactoryLabel);
		body.add(content);
		add(body);
		addStyleName("addFactoryPanel");
		
		// Listen for mouse events on the Add button.
		addFactoryButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				notifyAddHandlers(newFactoryNameTextBox.getText());
			}
		});

		// Listen for keyboard events in the input box.
		newFactoryNameTextBox.addKeyUpHandler(new KeyUpHandler() {
			public void onKeyUp(KeyUpEvent event) {	
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					notifyAddHandlers(newFactoryNameTextBox.getText());
					reset();
				}
			}
		});
		
		// Move cursor focus to the input box.
		reset();
	}
	
	public void addFactoryAddedHandler(IFactoryAddedHandler handler){
		if (handler!=null){
			addHandlers.add(handler);
		}
	}
	
	public void removeFactoryAddedHandler(IFactoryAddedHandler handler){
		if (handler!=null && addHandlers.contains(handler)){
			addHandlers.remove(handler);
		}
	}
	
	private void notifyAddHandlers(String name){
		for(IFactoryAddedHandler handler: addHandlers){
			handler.onFactoryAdded(name);
		}
	}
	
	private void reset(){
		newFactoryNameTextBox.setText("Fabrikname");
		newFactoryNameTextBox.setSelectionRange(0, newFactoryNameTextBox.getText().length());
		newFactoryNameTextBox.setFocus(true);
	}
	
	public interface IFactoryAddedHandler{
		public void onFactoryAdded(String name);
	}
}
